import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:yysk_app/enum/app_enum.dart';
import 'package:yysk_app/pages/main/main_controller.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/main/mine/mine_page_controller.dart';
import 'package:yysk_app/pages/nft_pages/danation/danation_choose_goods_controller.dart';
import 'package:yysk_app/pages/nft_pages/danation/danation_choose_goods_page.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/bulk_sales_and_cancellation_of_sales/bulk_sales_and_cancellation_of_sales_controller.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/bulk_sales_and_cancellation_of_sales/bulk_sales_and_cancellation_of_sales_page.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/my_collection_detail/my_collection_detail_controller.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/my_collection_detail/my_collection_detail_page.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/my_collection_list/my_collection_list_controller.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/my_collection_list/my_collection_list_page.dart';
import 'package:yysk_app/pages/nft_pages/market_pages/market_collection_buy/market_collection_buy_controller.dart';
import 'package:yysk_app/pages/nft_pages/market_pages/market_collection_buy/market_collection_buy_page.dart';
import 'package:yysk_app/pages/nft_pages/market_pages/market_rob_buy/market_rob_buy_controller.dart';
import 'package:yysk_app/pages/nft_pages/market_pages/market_rob_buy/market_rob_buy_page.dart';
import 'package:yysk_app/pages/nft_pages/my_blind/my_blind_list_controller.dart';
import 'package:yysk_app/pages/nft_pages/my_blind/my_blind_list_page.dart';
import 'package:yysk_app/pages/nft_pages/my_prop/prop_batch_gift/prop_batch_gift_controller.dart';
import 'package:yysk_app/pages/nft_pages/my_prop/prop_batch_gift/prop_batch_gift_page.dart';
import 'package:yysk_app/pages/nft_pages/my_prop/prop_list_controller.dart';
import 'package:yysk_app/pages/nft_pages/my_prop/prop_list_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/wallet/wallet_controller.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/wallet/wallet_page.dart';
import 'package:yysk_app/routes/initial_binding.dart';
import 'package:yysk_app/routes/routes_path/routes.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/utils/log_util.dart';
import 'package:leak_tracker/leak_tracker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

void main() {
  // _initLeakTracking();
  // 初始化 EasyLoading，配置遮罩层
  WidgetsFlutterBinding.ensureInitialized();
  // 锁定竖屏方向
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp, // 正方向竖屏
    // DeviceOrientation.portraitDown, // 倒方向竖屏（可选）
  ]).then((_) => runApp(MyApp()));
  EasyLoading.instance
    ..userInteractions = false
    ..backgroundColor = Colors.green
    ..maskColor = Colors.blue.withOpacity(0.5);
  Log.init;
  // configLoading();
}

void configLoading() {
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..progressColor = Colors.yellow
    ..backgroundColor = Colors.green
    ..indicatorColor = Colors.yellow
    ..textColor = Colors.yellow
    ..maskColor = Colors.blue.withOpacity(0.5)
    ..userInteractions = true
    ..dismissOnTap = false;
}

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

class MyApp extends StatelessWidget {
  MyApp({super.key});
  final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
     SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    statusBarColor: Colors.transparent, // 状态栏颜色
    statusBarIconBrightness: Brightness.dark, // 状态栏图标亮度
    systemNavigationBarColor: Colors.black, // 导航栏颜色
    systemNavigationBarIconBrightness: Brightness.dark, // 导航栏图标亮度
  ));
    ScreenHelper.init(context);
    return OKToast(
      child: GestureDetector(
        //收起ios键盘
        behavior: HitTestBehavior.translucent,
        onTap: () {
          hideKeyboard(context);
        },
        child: GetMaterialApp(
          defaultTransition: Transition.noTransition,
          routingCallback: (router) {
            consoleLog('路由监控去${router?.current} ,,,来自${router?.previous} ,来自${router?.isBack}');
            //商品下单重新选择地址后 刷新
            //道具转赠 刷新
            if (router!.current.contains(PropBatchGiftPage.path) &&
                router.previous.contains(PropBatchGiftPage.path)) {
              PropBatchGiftController controller = Get.find();
              if (controller.transferType.value == '3') {
                controller.getPropList();
              } else {
                controller.getBlindList();
              }
              controller.num.value = 0;
            }
            //道具详情 刷新
            if (router.current.contains(MyPropListPage.path) &&
                router.previous.contains(MyPropListPage.path)) {
              PropListController controller = Get.find();
              controller.getPropList();
              controller.getCount();
            }

            //藏品转赠 刷新
            if (router.current.contains(DanationChooseGoodsPage.path) &&
                router.previous.contains(DanationChooseGoodsPage.path)) {
              DanationChooseGoodsController controller = Get.find();
              controller.getList();
              controller.num.value = 0;
            }

            //盲盒转赠 刷新
            if (router.current.contains(MyBlindListPage.path) &&
                router.previous.contains(MyBlindListPage.path)) {
              MyBlindListController controller = Get.find();
              controller.getBlindList();
              controller.getCount();
            }
            //钱包 刷新
            // if (router.current.contains(WalletPage.path) &&
            //     router.previous.contains(WalletPage.path)) {
            //   WalletController controller = Get.find();
            //   controller.getBankList();
            // }
            //钱包 刷新
            // if (router.current.contains(WalletPage.path) &&
            //     router.previous.contains(WalletPage.path)) {
            //   WalletController controller = Get.find();
            //   controller.getBankList();
            // }
            //nft首页更新 刷新
            if (router.current.contains(MainPage.path) &&
                router.previous.contains(MainPage.path)) {
              try {
                MainController controller = Get.find();
                if (controller.modeType.value == AppModel.nft &&
                    controller.currentIndex.value == 3) {
                  //nft 我的页面
                  MinePageController minePageController = Get.find();
                  if (minePageController.type.value == 'Collection') {
                    minePageController.getCollectionList();
                  } else if (minePageController.type.value == 'blindbox') {
                    minePageController.getBlindList();
                  } else {
                    minePageController.getPropList();
                  }
                }
              } catch (e) {}
              ;
            }
            //银行卡刷新
            // if (router.current.contains(WithdrawPage.path) &&
            //     router.previous.contains(WithdrawPage.path)) {
            //   WithdrawController controller = Get.find();
            //   if (controller.isRefresh.value) {
            //     controller.amountController.text = '';
            //     controller.getInfo();
            //     controller.getBankList();
            //   }
            // }

            if (router.current.contains(WalletPage.path)) {
              try {
                Get.put(WalletController());
                WalletController walletController = Get.find();
                if (walletController.zhifuIsRefresh == true) {
                  walletController.startTime();
                }
              } catch (e) {
                consoleLog('$e');
              }
            }
            //批量出售数据
            if (router.current.contains(
                  BulkSalesAndCancellationOfSalesPage.path,
                ) &&
                router.previous.contains(
                  BulkSalesAndCancellationOfSalesPage.path,
                )&&router.isBack==true) {
              try {
                BulkSalesAndCancellationOfSalesController controller =
                    Get.find();
                if (controller.type.value == '1') {
                  controller.getCollectionListByCollectionId();
                } else {
                  controller.getMySellList();
                }
                controller.listSellChoose.value = [];
                 controller.listUnSellChoose.value = [];
              } catch (e) {
                consoleLog('$e');
              }
            }
             //我的单个列表数据
            if (router.current.contains(
                  MyCollectionListPage.path,
                ) &&
                router.previous.contains(
                  MyCollectionListPage.path,
                )&&router.isBack==true) {
              try {
                MyCollectionListController controller =
                    Get.find();
                  controller.getCollectionListByCollectionId();
             controller.getCollectionListByCollectionIdHead();
              } catch (e) {
                consoleLog('$e');
              }
            }
              //优先抢
            if (router.current.contains(
                  MarketRobBuyPage.path,
                ) &&
                router.previous.contains(
                  MarketRobBuyPage.path,
                )&&router.isBack==true) {
              try {
                MarketRobBuyController controller =
                    Get.find();
                  controller.getPlatWallet();
              } catch (e) {
                consoleLog('$e');
              }
            }
               //市场购买返回
            if (router.current.contains(
                  MarketCollectionBuyPage.path,
                ) &&
                router.previous.contains(
                  MarketCollectionBuyPage.path,
                )&&router.isBack==true) {
              try {
                MarketCollectionBuyController controller =
                    Get.find();
                      controller.totalPrice.value = '0';
                 controller.saleListChoose.value = [];
                  controller.getList();
                 

              } catch (e) {
                consoleLog('$e');
              }
            }
                 //我的藏品详情
            if (router.current.contains(
                  MyCollectionDetailPage.path,
                ) &&
                router.previous.contains(
                  MyCollectionDetailPage.path,
                )&&router.isBack==true) {
              try {
                MyCollectionDetailController controller =
                    Get.find();
                  controller.getdetail();
              } catch (e) {
                consoleLog('$e');
              }
            }
          },
          builder: EasyLoading.init(),
          title: '元宇时空',
          navigatorObservers: [routeObserver],
          navigatorKey: navigatorKey,
          theme: ThemeData(
            // colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            scaffoldBackgroundColor: AppColors.backgroundColorBlack,
            useMaterial3: true,
          ),
          initialRoute: Routes.init,
          getPages: Routes.routes,
          initialBinding: InitialBinding(),
          locale: const Locale('zh', 'CH'),
          localizationsDelegates: const [
            GlobalCupertinoLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          supportedLocales: const [Locale('zh', 'CH'), Locale('en', 'US')],
        ),
      ),
    );
  }
}

void hideKeyboard(BuildContext context) {
  FocusScopeNode currentFous = FocusScope.of(context);
  if (!currentFous.hasPrimaryFocus && currentFous.focusedChild != null) {
    FocusManager.instance.primaryFocus!.unfocus();
  }
}

//在 debug 模式下会持续检查内存溢出情况,其他模式下无效果
void _initLeakTracking() {
  //打印保存堆栈信息
  LeakTracking.phase = const PhaseSettings(
    leakDiagnosticConfig: LeakDiagnosticConfig(
      collectRetainingPathForNotGCed: true,
      collectStackTraceOnStart: true,
      collectStackTraceOnDisposal: true,
    ),
  );
  LeakTracking.start(
    config: LeakTrackingConfig(
      onLeaks: (s) async {
        //打印当前内存溢出整体情况
        debugPrint("onLeak: ${s.toJson()}");

        //收集所有内存溢出异常,调用这个方法后会清空LeakTracking里的所有已收集的异常
        final leaks = await LeakTracking.collectLeaks();

        //一些组件需要在 Widget 回收之后调用其 dispose 方法，通过此可以检测出未调用 dispose 方法的组件
        //a disposable object was GCed, without being disposed first.
        //This means that the object's disposable content is using memory after the object is no longer needed.
        for (var n in leaks.notDisposed) {
          debugPrint(
            n.toYaml("内存溢出检查=== 已经回收的对象 notDisposed:", phasesAreTests: true),
          );
        }
        //统计未进行内存回收的对象
        //an object was disposed, but not GCed after certain number of GC events.
        //This means that a reference to the object is preventing it from being garbage collected after it's no longer needed.
        for (var n in leaks.notGCed) {
          debugPrint(
            n.toYaml("内存溢出检查=== 没有回收的对象 notGCed:", phasesAreTests: true),
          );
        }
        //统计对象进行了内存回收,但是回收时间不及时
        //an object was disposed and then GCed, but GC happened later than expected.
        //This means the retaining path was holding the object in memory for some period, but then disappeared.
        for (var n in leaks.gcedLate) {
          debugPrint(
            n.toYaml(
              "内存溢出检查=== 内存回收,但是回收时间不及时  gcedLate:",
              phasesAreTests: true,
            ),
          );
        }
      },
    ),
  );
  FlutterMemoryAllocations.instance.addListener(
    (ObjectEvent event) => LeakTracking.dispatchObjectEvent(event.toMap()),
  );
}
